package com.xmb.common.service.wx.impl;

import com.alibaba.fastjson.JSONObject;
import com.github.binarywang.wxpay.bean.notify.WxPayRefundNotifyResult;
import com.github.binarywang.wxpay.exception.WxPayException;
import com.github.binarywang.wxpay.service.WxPayService;
import com.github.binarywang.wxpay.service.impl.WxPayServiceImpl;
import com.xmb.common.constants.PayStatusEnum;
import com.xmb.common.dao.XmbWechatPaymentRefundMapper;
import com.xmb.common.entity.XmbWechatPaymentRefund;
import com.xmb.common.service.wx.WxPayRefundNotifyService;
import org.apache.rocketmq.client.exception.MQBrokerException;
import org.apache.rocketmq.client.exception.MQClientException;
import org.apache.rocketmq.client.producer.DefaultMQProducer;
import org.apache.rocketmq.client.producer.SendResult;
import org.apache.rocketmq.common.message.Message;
import org.apache.rocketmq.remoting.exception.RemotingException;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;

/**
 * Created by lyndon on 2019/3/27.
 */
@Service
public class WxPayRefundNotifyServiceImpl implements WxPayRefundNotifyService {
    private static final Logger logger = LoggerFactory.getLogger(WxPayRefundNotifyServiceImpl.class);

    @Resource
    private XmbWechatPaymentRefundMapper paymentRefundMapper;

    private WxPayService wxPayService;

    @Autowired
    private DefaultMQProducer mqProducer;

    public void payRefundNotify (String xmlData) throws WxPayException{
        logger.info("resultXml:" + xmlData);
        wxPayService = new WxPayServiceImpl();
        final WxPayRefundNotifyResult refundNotifyResult = wxPayService.parseRefundNotifyResult(xmlData);
        if ("SUCCESS".equals(refundNotifyResult.getResultCode())) {
            // 更新支付订单表
            XmbWechatPaymentRefund wechatPaymentRefund = this.updateXmbWechatPaymentRefund(refundNotifyResult);
            if (wechatPaymentRefund != null) {
                // 通知业务系统
                this.sendMsg(this.getNotifyBusinessMsg(wechatPaymentRefund));
                this.sendMsg(this.getDelayCheckMsg(wechatPaymentRefund));
            }
        } else {
            logger.info("退款失败,错误编号为:{},错误信息为:{}",refundNotifyResult.getErrCode(),refundNotifyResult.getErrCodeDes());
        }
    }

    @Override
    public XmbWechatPaymentRefund updateXmbWechatPaymentRefund(WxPayRefundNotifyResult refundNotifyResult) {
        XmbWechatPaymentRefund paymentRefund = new XmbWechatPaymentRefund();
        paymentRefund.setMerchantRefundNo(refundNotifyResult.getReqInfo().getOutRefundNo());
        XmbWechatPaymentRefund wechatPaymentRefund
                = paymentRefundMapper.selectXmbWechatPaymentRefund(paymentRefund);
        if (wechatPaymentRefund != null) {
            wechatPaymentRefund.setRefundStatus(PayStatusEnum.refunded.name());
            wechatPaymentRefund.setWxRefundNo(refundNotifyResult.getReqInfo().getRefundId());
            paymentRefundMapper.updateByPrimaryKeySelective(wechatPaymentRefund);
        }
        return wechatPaymentRefund;
    }

    @Override
    public Message getNotifyBusinessMsg(XmbWechatPaymentRefund wechatPaymentRefund) {
        String transType = wechatPaymentRefund.getMerchantTransactionNo().split("_")[1];
        JSONObject msgObject = new JSONObject(2);
        msgObject.put("transType",transType);
        msgObject.put("senceId",wechatPaymentRefund.getSenceId());
        Message sendMsg = new Message("payOrder_","shopping_",msgObject.toString().getBytes());
        return sendMsg;
    }

    @Override
    public Message getDelayCheckMsg(XmbWechatPaymentRefund wechatPaymentRefund) {
        String transType = wechatPaymentRefund.getMerchantTransactionNo().split("_")[1];
        JSONObject msgObject = new JSONObject(2);
        msgObject.put("transType",transType);
        msgObject.put("senceId",wechatPaymentRefund.getSenceId());
        Message sendMsg = new Message("payOrder_","shopping_",msgObject.toString().getBytes());
        sendMsg.setDelayTimeLevel(8); // 延迟5分钟消费
        return sendMsg;
    }

    @Override
    public void sendMsg(Message sendMsg) {
        SendResult sendResult = null;
        try {
            sendResult = mqProducer.send(sendMsg);
            logger.info("消息发送响应信息："+sendResult.toString());
        } catch (MQClientException | RemotingException | MQBrokerException | InterruptedException e) {
            e.printStackTrace();
            logger.error("消息发送出现异常："+e.getMessage());
        }
    }

}
